#include "ConnectionFilter.h"
#include "Connection.h"
extern "C" {
#include "event2/event.h"
#include "event.h"
};
ConnectionFilter::ConnectionFilter( Connection* conn )
{
	m_conncetion = conn;
}


static int getIntFormBuf(unsigned char* buf )
{
	int val1 = buf[0] ? ((int)buf[0]) << 24 : 0;
	int val2 = buf[1] ? ((int) buf[1]) << 16 : 0;
	int val3 = buf[2] ? ((int)buf[2]) << 8 : 0;
	int val4 =  buf[3];

	return val1 + val2 + val3+ val4;
}

static void intToBuf( int data,  unsigned char* buf )
{
	buf[0] = (data >> 24) & 0xff;
	buf[1] = (data >> 16) & 0xff;
	buf[2] = (data >> 8) & 0xff;
	buf[3] = data & 0xff;
}
void ConnectionFilter::setHandler( ConnectionFilterHandler* filter )
{
	m_handler = filter;
}

void ConnectionFilter::sendData( char* data, int len )
{
	unsigned char buf[4] = {};
	intToBuf(len, buf);
	m_conncetion->sendData((char*)buf, 4);
	m_conncetion->sendData(data, len);
}

void ConnectionFilter::onData( Connection* conn )
{
	bufferevent* bev = conn->getBev();
	evbuffer* input = bev->input;

	if(evbuffer_get_length(input) < 4) {
		return;
	}

	char* data = (char*)evbuffer_pullup(input, 4);

	if(!data) {
		return;
	}

	int dataLen = getIntFormBuf((unsigned char*)data);

	if(dataLen == 0) {
		return;
	}
	
	if(evbuffer_get_length(input) < (size_t)dataLen + 4) {
		return;
	}
	char* dataStart = (char*)evbuffer_pullup(input, 4 + dataLen) + 4;

	if(this->m_handler) {
		this->m_handler->onFilterData(this, dataStart, dataLen);
	}
	evbuffer_drain(input, dataLen + 4);
}

void ConnectionFilter::onConnected( Connection* conn )
{

}

void ConnectionFilter::onClose( Connection* conn )
{

}
